<template>
  <router-view v-slot="{ Component }">
    <keep-alive>
      <component :is="Component"
                 v-if="$route.meta.keepAlive"
                 :key="$route.path" />
    </keep-alive>
    <component :is="Component"
               v-if="!$route.meta.keepAlive" />
  </router-view>
</template>
<script>
import { getCurrentInstance } from 'vue';
import {WebSocketClient} from '@/common/webScoket';
import eventBus from '@/common/eventBus'
import { ElNotification } from 'element-plus'
import WaterMark from '@/common/watermark'
import { unApprove } from '@/api/chartdb'
import {userStoreWithOut} from '@/stores/modules/userStore'
// import {toRefs} from 'vue'
// const userStore = userStoreWithOut()
// const {userName} = toRefs(userStore)

const sendQuestion = (message) => {
  ElNotification.closeAll(); // 跳转前关闭通知
  eventBus.emit('sendMsg', message)
};

export default {
  data(){
    return {
      notifications:[],
      app:getCurrentInstance()
    }
  },
  created() {
    if(!localStorage.getItem("mode")){
      let mode="light"
      localStorage.setItem("mode",mode)
    }
    // WaterMark.set(localStorage.getItem("uname")+" "+localStorage.getItem("staffName")+" "+localStorage.getItem("orgName"));
  },
  computed:{
    includedComponents(){
      return this.$route.meta.keepAlive
    },
    userInfo() {
      return userStoreWithOut().getUserInfo
    },
  },
  watch: {
    userInfo: {
      handler(newVal) {
        console.log("newVal-====>",newVal)
        if(newVal&&newVal.userId){
          this.initSocket(newVal.userId)
        }
      },
      immediate: false,
      deep: true // 开启深度监听
    }
  },
  mounted() {
    if(window.performance.getEntriesByType("navigation")[0].type=="reload"){
      this.initSocket(this.userInfo.userId)
    }
  },
  methods: {
    //初始化消息
    initSocket(uname){
      if(!uname) return false
      this.app.appContext.config.globalProperties.$WebSocketClientInstance = new WebSocketClient(uname);
      this.app.appContext.config.globalProperties.$WebSocketClientInstance.initWebSocket()
      // 添加socket通知监听
      window.addEventListener('onmessageWS', this.getSocketData)
      //查询待审批信息条数通知当前用户
      this.unApprove()
    },
    // 收到消息处理
    getSocketData(res) {
      var vm = this;
      const h = this.$createElement;
      console.log("res.detail======>",res.detail)
      if(res.detail.data=="连接成功！"){
        return false
      }

      if (res.detail.data.indexOf("msgType") >= 0){
        let resJson = JSON.parse(res.detail.data);
        if (resJson && resJson.msgType == 1){
          ElNotification({
            title: '消息提醒',
            message: "问题【<span style=\"color: #5C7CFF;margin-left:5px;cursor: pointer\">" + resJson.message + '</span>】已处理，请尝试重新提问！',
            type: 'success',
            dangerouslyUseHTMLString: true,
            position: 'bottom-right',
            onClick() {
              sendQuestion(resJson.message);
            },
          })
        }
        return
      }

      let json=JSON.parse(res.detail.data);
      let notify=""
      if(json.type=="apply"){
        notify = ElNotification({
          title: '您有待处理信息',
          message: `<div style="cursor: pointer;display: flex;flex-direction: column">
                    <span>
                      <span style="color: #5C7CFF">${json.applyName}</span>申请<span style="color: #5C7CFF">${json.tableName}</span>数据权限请尽快处理
                    </span>
                    <span style="color: #5C7CFF;margin-left: 10px;">前往 >></span></div>`,
          duration: 0,
          dangerouslyUseHTMLString: true,
          onClick() {
            vm.gotoApprove()
          },
          type: 'info',
        })
      }else if(json.type=="approve"){
        notify = ElNotification({
          title: '新消息',
          message: `<div style="cursor: pointer">您申请的
                    <span style="color: #5C7CFF;">${json.tableName}</span>数据权限审批${json.message}
                    </div>`,
          duration: 0,
          dangerouslyUseHTMLString: true,
          onClick() {
            //vm.gotoApprove()
          },
          type: 'success',
        })
      }else  if(json.type=="unApprove"){
        notify = ElNotification({
          title: '您有待处理信息',
          message: `<div style="cursor: pointer;display: flex;flex-direction: column">
                    <span>您有<span style="color: #5C7CFF">${json.count}</span>条待处理消息，请尽快处理！</span>
                    <span style="color: #5C7CFF;">前往 >></span>
                    </div>`,
          duration: 0,
          dangerouslyUseHTMLString: true,
          onClick() {
            vm.gotoApprove()
          },
          type: 'info',
        })
      }
      this.notifications.push(notify)
    },
    gotoApprove(){
      this.closeAllNotification();
      this.$router.push({path:'/approve'});
    },
    //关闭所有通知
    closeAllNotification() {
      for (let key in this.notifications) {
        console.log("key======>",key);
        this.notifications[key].close()
        delete this.notifications[key]
      }
    },
    //查询待审批信息条数通知当前用户
    unApprove(){
      unApprove().then((res) => {
        console.log("unApprove=====>",res)
      })
    }
  }
}
</script>
<style>
#app{
  font-family: SourceHanSansCN-Normal;
  height: 100%;
}
.el-button{
  font-family: SourceHanSansCN-Normal;
}
.customWidth{
  width: 80% !important;
}
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: #fff;
}

.el-popper.is-customized .el-popper__arrow::before {
  background: #fff;
  right: 0;
}

.log-dialog{
  width: 100%;
  border-radius: 0px;
}
.log-dialog .el-dialog__body{
  padding: 0px 20px !important;
}
.json-dialog{
  width: 80%;
}
.json-dialog .el-dialog__body{
  padding: 20px 20px !important;
  max-height: 500px;
}
.json-edit-dialog{
  width: 90%;
}
.json-edit-dialog .el-dialog__body{
  padding: 20px 20px !important;
  height: 600px;
  overflow: auto;
}
.normal-dialog .el-dialog__body{
  padding: 0px 20px !important;
}
.json-dialog .el-dialog__body .json-div{
  padding: 0px 10px !important;
  max-height: 460px;
  overflow: auto;
}
.my-tooltip{
  max-width: 25% !important;
  padding: .05rem .1rem;
}
</style>
